package com.bluemobi.framework.pay.alipay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;

/**
 * 
 * @ClassName AliPayUtil
 * @Description 支付宝支付工具类
 */
public class AliPayUtil {

	/**
	 * 
	 * @Title: createOrder @Description: 下单 @param orderPayCode 订单支付编号 @param
	 *         orderAmount 订单金额（单位：元） @param body 描述 @param subject 副标题 @param
	 *         noticeUrl 支付通知url @return @throws
	 */
	public static String createAppOrder(String orderPayCode, String orderAmount, String body, String subject,
			String noticeUrl) {
		String retStr = "";

		// 实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
				AlipayConfig.APP_ID, AlipayConfig.APP_RSA2_PRIVATE_KEY, "json", AlipayConfig.CHARSET,
				AlipayConfig.APP_ALI_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);

		// 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();

		// SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(body);
		model.setSubject(subject);
		model.setOutTradeNo(orderPayCode);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(orderAmount);
		model.setProductCode("QUICK_MSECURITY_PAY");
		request.setBizModel(model);
		request.setNotifyUrl(noticeUrl);
		try {
			// 这里和普通的接口调用不同，使用的是sdkExecute
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
			retStr = response.getBody();// 就是orderString 可以直接给客户端请求，无需再做处理。
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}

		return retStr;
	}

	/**
	 * 
	 * @Title: verify @Description: 支付宝验签 @param request @return @throws
	 *         AlipayApiException @throws
	 */
	public static Map<String, String> verify(HttpServletRequest request) throws AlipayApiException {
		Map<String, String> params = new HashMap<String, String>();
		@SuppressWarnings("unchecked")
		Map<String, String[]> requestParams = request.getParameterMap();

		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		System.out.println(params.toString());
		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		// boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
		// publicKey, String charset, String sign_type)
		boolean flag = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALI_PUBLIC_KEY, AlipayConfig.CHARSET,
				AlipayConfig.SIGN_TYPE);

		if (flag) {
			params.put("verifyResult", "1");
		} else {
			params.put("verifyResult", "0");
		}

		return params;
	}

	public static void main(String[] args) {
		String orderPayCode = "test123122133";
		String body = "测试订单";
		String orderAmount = "1";
		String noticeUrl = "http://127.0.0.1:8080";
		String subject = "测试订单";

		String retStr = createAppOrder(orderPayCode, orderAmount, body, subject, noticeUrl);

		System.out.println(retStr);
	}
}
